package com.qd.p2p.baofoo.util;

import java.io.File;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

public class HttpRequestUtil {
	/**
	 * 向指定URL发送GET方法的请求[字符流]
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			URLConnection connection = realUrl.openConnection();
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.connect();
			Map<String, List<String>> map = connection.getHeaderFields();
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求[字符流]
	 */
	public static String sendHttpPost(String url, String param) throws Exception {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestProperty("Accept-Charset", "utf-8");
			conn.setRequestProperty("contentType", "utf-8");
			out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求[字符流],导出为Excel文件
	 */
	public static String sendHttpPostExcel(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);

			String fileName = "baofoo_" + OrderNoUtil.getInstance().getSerialNumber() + ".xlsx";
			String baofooExcelPath = getWebAppPath()  + "baofooExcelDir/";
			File baofooExcelDir = new File(baofooExcelPath);
			if (!baofooExcelDir.exists()) {
				baofooExcelDir.mkdir();
			}
			String filePath = baofooExcelPath + fileName;
			File file = new File(filePath);
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			if (!file.exists()) {
				file.createNewFile();
			}
			IOUtils.copy(conn.getInputStream(), fileOutputStream);
			fileOutputStream.flush();
			fileOutputStream.close();
			return "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><crs><file_path>" + filePath + "</file_path></crs>";
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * post方式请求服务器(https协议)
	 */
	public static String sendHttpsPost(String url, String param, String charset) throws NoSuchAlgorithmException, KeyManagementException, IOException {
		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());

		URL console = new URL(url);
		HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
		conn.setSSLSocketFactory(sc.getSocketFactory());
		conn.setRequestProperty("Accept-Charset", charset);
		conn.setRequestProperty("contentType", charset);
		conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
		conn.setDoOutput(true);
		conn.connect();
		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		out.write(param.getBytes(charset));
		// 刷新、关闭
		out.flush();
		out.close();
		InputStream is = conn.getInputStream();
		if (is != null) {
			BufferedReader br = new BufferedReader(new InputStreamReader(is, charset));  
            StringBuffer resultBuffer = new StringBuffer();  
            String tempLine = null;  
            while ((tempLine = br.readLine()) != null) {  
                resultBuffer.append(tempLine);  
            }
            is.close();
			return resultBuffer.toString();
		}
		return null;
	}

	/**
	 * post方式请求服务器(https协议)[字符流],导出为Excel文件
	 */
	public static String sendHttpsPostExcel(String url, String param, String charset) throws NoSuchAlgorithmException, KeyManagementException, IOException {
		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());

		URL console = new URL(url);
		HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
		conn.setSSLSocketFactory(sc.getSocketFactory());
		conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
		conn.setDoOutput(true);
		conn.connect();

		String fileName = "baofoo_" + OrderNoUtil.getInstance().getSerialNumber() + ".xlsx";
		String baofooExcelPath = getWebAppPath()  + "baofooExcelDir/";
		File baofooExcelDir = new File(baofooExcelPath);
		if (!baofooExcelDir.exists()) {
			baofooExcelDir.mkdir();
		}
		String filePath = baofooExcelPath + fileName;
		File file = new File(filePath);
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		if (!file.exists()) {
			file.createNewFile();
		}
		IOUtils.copy(conn.getInputStream(), fileOutputStream);
		fileOutputStream.flush();
		fileOutputStream.close();

		return "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><crs><file_path>" + filePath + "</file_path></crs>";
	}

 	private static class TrustAnyTrustManager implements X509TrustManager {

		public void checkClientTrusted(X509Certificate[] chain, String authType) {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}

	private static class TrustAnyHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

	/**
	 * 获取该类所在容器的webapp目录
	 *
	 * @author Kaiju Zhao
	 */
	private static String getWebAppPath() {
		String className = HttpRequestUtil.class.getName();
		String classNamePath = className.replace(".", "/") + ".class";
		URL is = HttpRequestUtil.class.getClassLoader().getResource(classNamePath);
		String path = is.getFile();
		path = StringUtils.replace(path, "%20", " ");
		path =  StringUtils.removeStart(path, "/");
		path = path.split("WEB-INF")[0];

		return path;
	}
}